﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using XQ.WeChatOfficialAccount.BLL.Common;
using XQ.WeChatOfficialAccount.BLL.Sys;
using XQ.WeChatOfficialAccount.DAL.DAL.Common;
using XQ.WeChatOfficialAccount.DAL.Model;
using XQ.WeChatOfficialAccount.DAL.Model.Sys;
using XQ.WeChatOfficialAccount.WebAPI.Common;
using XQ.WeChatOfficialAccount.WebAPI.Models;

namespace XQ.WeChatOfficialAccount.WebAPI.Controllers.System
{
    /// <summary>
    /// 小程序相关接口
    /// </summary>
    public class AppletsController : ApiController
    {
        UserBLL userBLL = new UserBLL();

        /// <summary>
        /// 获取openid
        /// </summary>
        /// <param name="code">临时code</param>
        /// <returns></returns>
        [Route("api/Applets/GetOpenid")]
        [HttpGet]

        public ResultModel GetOpenid(string code)
        {
            ResultModel resultModel = new ResultModel();
            try
            {
                LogBll.Instance.WriteLog(LogBll.LogType.Other, "", 0, "获取openid", "", "", "", "Api/Applets/GetOpenid:" + code);
                WechatUserModel wechatUserModel = new WechatUserModel();
                wechatUserModel.Openid = WxLoginHelper.GetOpenid(code);
                //如果是系统用户就增加Token返回值
                UserExModel userExModel = userBLL.GetUserByOpenid(wechatUserModel.Openid);
                if (userExModel != null && !string.IsNullOrEmpty(wechatUserModel.Openid))
                {
                    wechatUserModel.Token = TokenHelper.CreateToken(userExModel.id, userExModel.DepartmentID, (int)userExModel.RoleID);
                    wechatUserModel.RoleName = userExModel.RoleName;
                }
                resultModel.data = wechatUserModel;
            }
            catch (Exception ex)
            {
                LogBll.Instance.WriteErrLog("", 0, "获取openid", "", "", "", ex.Message, "", "AppletsController", "GetOpenid");
                resultModel.success = false;
                resultModel.message = ex.Message;
                resultModel.code = "10001";
            }
            return resultModel;
        }
    }
}